package imageclipper

import (
	"errors"
	"image"
	"log"
	"os"
	"path"
	"path/filepath"
)

/*
验证源图像文件的瓦片大小
	1. 规定尺寸是 2448 x 2048
	params:
		file_path: 文件路径
		extension: 图片扩展名
	returns:
		err: error
	example:
		verfiySourceTileSize("100x", "jpg")
*/
func verfiySourceTileSize(file_path string, extension string) (tileHeight, tileWidth int, err error) {

	matches, err := filepath.Glob(path.Join(file_path, "*."+extension))

	if err != nil {
		return
	}

	if len(matches) == 0 {
		err = errors.New("no file")
		return
	}

	for _, fp := range matches {
		log.Println(fp)
		f, err := os.Open(fp)
		if err != nil {
			return tileHeight, tileWidth, err
		}
		defer f.Close()
		jpg, _, err := image.Decode(f)
		if err != nil {
			return tileHeight, tileWidth, err
		}
		if tileHeight == 0 && tileWidth == 0 {
			tileWidth = jpg.Bounds().Size().X
			tileHeight = jpg.Bounds().Size().Y
		}
		if tileWidth != jpg.Bounds().Size().X || tileHeight != jpg.Bounds().Size().Y {
			return tileHeight, tileWidth, errors.New("tile size is error")
		}
	}

	return tileHeight, tileWidth, nil
}

/*
验证参数
	1. 验证输入参数的有效性
	params:
		x, y:               从左上角坐标开始裁剪
		width, height:      裁剪后的宽度、高度
		cols, rows:         裁剪前列数、行数
	returns:
		new_cols, new_rows: 裁剪后列数、行数
*/
func verifyParameter(x, y, width, height, cols, rows int) (new_cols, new_rows int, err error) {

	if (width % tileWidth) > 0 {
		err = errors.New("width 不是 2448 的倍数")
		return
	}

	if (height % tileHeight) > 0 {
		err = errors.New("height 不是 2048 的倍数")
		return
	}

	if x < 0 {
		err = errors.New("裁剪区域超出范围")
		return
	}

	if y < 0 {
		err = errors.New("裁剪区域超出范围")
		return
	}

	if (x + width) > (cols * tileWidth) {
		err = errors.New("裁剪区域超出范围")
		return
	}

	if (y + height) > (rows * tileHeight) {
		err = errors.New("裁剪区域超出范围")
		return
	}

	new_cols = width / tileWidth
	new_rows = height / tileHeight

	return
}
